package ai

import (
	"context"
	"net/http"
	"paper-pro/app/chat/api/internal/logic/ai"
	"paper-pro/app/chat/api/internal/metrics"
	"paper-pro/app/chat/api/internal/svc"
	"paper-pro/app/chat/api/internal/types"
	"paper-pro/pkg/result"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

func completionsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		flusher := w.(http.Flusher) // 不成功直接抛异常，阻止服务运行

		var req types.UserMsg
		if err := httpx.Parse(r, &req); err != nil {
			result.SSEParamErrorResult(r, w, flusher, err)
			return
		}
		logx.WithContext(r.Context()).Infof("shenll receive msg id = %s", req.ChatMsg.Id)
		req.ChatMsg.Id = ""

		ctx, cancel := context.WithCancel(r.Context())
		defer cancel()
		l := ai.NewCompletionsLogic(ctx, svcCtx)
		recvChan := l.Completions(&req)

		// 记录请求开始时间
		startTime := time.Now()
		path := r.URL.Path
		firstResponse := true
		lastResponseTime := time.Time{}
		for {
			select {
			case <-r.Context().Done():
				result.SSEResult(r, w, flusher, nil, ai.ErrCompletionsCancel)
				return
			case recv, ok := <-recvChan:
				if !ok {
					return
				}
				if firstResponse {
					duration := time.Since(startTime).Seconds()
					metrics.SSEFirstResponseDuration.WithLabelValues(path).Observe(duration)
					firstResponse = false
					lastResponseTime = time.Now()
				} else {
					// 计算并记录响应间隔时间
					duration := time.Since(lastResponseTime).Seconds()
					metrics.SSEIntervalDuration.WithLabelValues(path).Observe(duration)
					lastResponseTime = time.Now()
				}
				if recv.Err != nil {
					result.SSEResult(r, w, flusher, recv.AiReply, recv.Err)
					return
				}
				result.SSEResult(r, w, flusher, recv.AiReply, nil)
			}
		}
	}
}
